//
//  NibLoadable.swift
//  iDev
//
//  Created by lbxia on 2021/8/29.
//

import Foundation
import Cocoa

protocol NibLoadable {
    static var nibName: String? { get }
    static func loadFromNib(in bundle: Bundle, index: Int) -> Self?
}

extension NibLoadable where Self: NSView {

    static var nibName: String? {
        return String(describing: Self.self)
    }

    static func loadFromNib(in bundle: Bundle = Bundle.main,index: Int = 0) -> Self? {
        guard let nibName = nibName else { return nil }
        var topLevelArray: NSArray? = nil
        bundle.loadNibNamed(NSNib.Name(nibName), owner: self, topLevelObjects: &topLevelArray)
        guard let results = topLevelArray else { return nil }
        
        
        let arrayViews: Array? = results.filter { $0 is Self }
        
        if let views = arrayViews, views.count  > index {
            
            return views[index] as? Self
        }
        
        return nil
    }
}
